package redisson.rest;

import java.time.Duration;
import java.util.concurrent.TimeUnit;

import java.util.concurrent.TimeUnit;

import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import com.baomidou.lock.annotation.Lock4j;
import com.esotericsoftware.minlog.Log;

import jodd.util.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

@Slf4j
//@RestController
@RequestMapping("/mock")
public class MockController {
//		操作	Redis 命令	key 不存在			key 已存在				典型用途
//		setIfAbsent		SET key value NX	写入成功	放弃，返回 false	抢锁/占位
//		setIfExists		SET key value XX	放弃，返回 false	覆盖成功	更新已有数据
//		compareAndSet	当前值 == expect		覆盖/删除	放弃				乐观锁、状态机		

	@Autowired
	RedissonClient redissonClient;

	@GetMapping("/lock")
	@Lock4j(keys = { "#key" }, acquireTimeout = 1000, expire = 10000)
	public String lockMethod(@RequestParam String key) {
		ThreadUtil.sleep(5000);
		return key;
	}

	@PostMapping("/post-lock")
	@Lock4j(keys = { "#post.testId" }, acquireTimeout = 1000, expire = 10000)
	public String postLock(@RequestBody PostLock post) {
		ThreadUtil.sleep(5000);
		return post.getTestId();
	}

	@PostMapping("/exist")
	public boolean exist(@RequestBody PostLock post) {
		// 判断 + 原子占位，返回 true 表示“之前不存在，现在被我占了”
		boolean absent = redissonClient.getBucket("field:" + post.getTestId()).setIfAbsent("1", Duration.ofMinutes(2));
		if (absent) {
			log.info("### 已占位该key,可执行逻辑!");
		}

		return absent;
	}
}
